Laravel Passport——OAuth2 API 认证系统源码解析(上)

前言

在 Laravel 中,实现基于传统表单的登陆和授权已经非常简单,但是如何满足 API 场景下的授权需求呢?在 API 场景里通常通过令牌来实现用户授权,而非维护请求之间的 Session 状态。在 Laravel 项目中使用 Passport 可以轻而易举地实现 API 授权认证,Passport 可以在几分钟之内为你的应用程序提供完整的 OAuth2 服务端实现。

首先我们可以先了解一下 OAuth2 : 理解OAuth 2.0

可以看出来,OAuth2 的授权模式分为 4 种,相应的 Passport 的授权模式也是 4 中。下面,我们就会逐一进行源码分析。

Passport 服务的注册启动

  1. class PassportServiceProvider extends ServiceProvider
  2. {
  3. public function register()
  4. {
  5. $this->registerAuthorizationServer();
  6. $this->registerResourceServer();
  7. $this->registerGuard();
  8. }
  9. }

我们知道 OAuth2 大致由 客户客户端认证服务器资源服务器 等构成。 在这里,我们扮演着 认证服务器资源服务器 的角色。

认证服务器注册

  1. protected function registerAuthorizationServer()
  2. {
  3. $this->app->singleton(AuthorizationServer::class, function () {
  4. return tap($this->makeAuthorizationServer(), function ($server) {
  5. $server->enableGrantType(
  6. $this->makeAuthCodeGrant(), Passport::tokensExpireIn()
  7. );
  8. $server->enableGrantType(
  9. $this->makeRefreshTokenGrant(), Passport::tokensExpireIn()
  10. );
  11. $server->enableGrantType(
  12. $this->makePasswordGrant(), Passport::tokensExpireIn()
  13. );
  14. $server->enableGrantType(
  15. new PersonalAccessGrant, new DateInterval('P1Y')
  16. );
  17. $server->enableGrantType(
  18. new ClientCredentialsGrant, Passport::tokensExpireIn()
  19. );
  20. if (Passport::$implicitGrantEnabled) {
  21. $server->enableGrantType(
  22. $this->makeImplicitGrant(), Passport::tokensExpireIn()
  23. );
  24. }
  25. });
  26. });
  27. }

AuthorizationServer 认证服务器是 League OAuth2 server 的一个类,是 League 关于 OAuth2 的实现类。这个认证服务器类需要 5 个参数,分别代表 客户端token 令牌scope 作用范围加密私钥加密 key

  1. class AuthorizationServer implements EmitterAwareInterface
  2. {
  3. public function __construct(
  4. ClientRepositoryInterface $clientRepository,
  5. AccessTokenRepositoryInterface $accessTokenRepository,
  6. ScopeRepositoryInterface $scopeRepository,
  7. $privateKey,
  8. $encryptionKey,
  9. ResponseTypeInterface $responseType = null
  10. ) {
  11. $this->clientRepository = $clientRepository;
  12. $this->accessTokenRepository = $accessTokenRepository;
  13. $this->scopeRepository = $scopeRepository;
  14. if ($privateKey instanceof CryptKey === false) {
  15. $privateKey = new CryptKey($privateKey);
  16. }
  17. $this->privateKey = $privateKey;
  18. $this->encryptionKey = $encryptionKey;
  19. $this->responseType = $responseType;
  20. }
  21. }

这些不同的 Repository 均是各个接口类,这些类规定了各个部分的功能。Passport 实现了上述几个接口类:

  1. public function makeAuthorizationServer()
  2. {
  3. return new AuthorizationServer(
  4. $this->app->make(Bridge\ClientRepository::class),
  5. $this->app->make(Bridge\AccessTokenRepository::class),
  6. $this->app->make(Bridge\ScopeRepository::class),
  7. $this->makeCryptKey('oauth-private.key'),
  8. app('encrypter')->getKey()
  9. );
  10. }
  11. protected function makeCryptKey($key)
  12. {
  13. return new CryptKey(
  14. 'file://'.Passport::keyPath($key),
  15. null,
  16. false
  17. );
  18. }

oauth-private.key 这个私钥由 php artisan passport:keys 命令生成。encrypter 的加密 key.env 文件的 key 属性。

构建认证服务器之后,还要对认证服务器注册授权方式。 Passport 的授权方式有传统的 OAuth2 : 授权码模式密码模式隐性模式客户端模式,还有 刷新令牌模式个人授权模式 等。

  1. protected function makeAuthCodeGrant()
  2. {
  3. return tap($this->buildAuthCodeGrant(), function ($grant) {
  4. $grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn());
  5. });
  6. }
  7. protected function buildAuthCodeGrant()
  8. {
  9. return new AuthCodeGrant(
  10. $this->app->make(Bridge\AuthCodeRepository::class),
  11. $this->app->make(Bridge\RefreshTokenRepository::class),
  12. new DateInterval('PT10M')
  13. );
  14. }

资源服务器注册

类似的, ResourceServer 也是 League 的资源服务器类:

  1. protected function registerResourceServer()
  2. {
  3. $this->app->singleton(ResourceServer::class, function () {
  4. return new ResourceServer(
  5. $this->app->make(Bridge\AccessTokenRepository::class),
  6. $this->makeCryptKey('oauth-public.key')
  7. );
  8. });
  9. }

guard 注册

当我们已经构建好 Passport 服务之后,我们只要利用中间件 Auth:api 就可以利用 Passport 验证 api 的合法性。具体的原理是 中间件 Auth 的参数 api 是指定 guard 的名称,例如 webapi,如果调用的是 apiguard 那么就会创建相应的 passport 驱动器:

  1. 'guards' => [
  2. 'web' => [
  3. 'driver' => 'session',
  4. 'provider' => 'users',
  5. ],
  6. 'api' => [
  7. 'driver' => 'passport',
  8. 'provider' => 'users',
  9. ],
  10. ],

passportguard 驱动器就是这个 TokenGuard:

  1. protected function registerGuard()
  2. {
  3. Auth::extend('passport', function ($app, $name, array $config) {
  4. return tap($this->makeGuard($config), function ($guard) {
  5. $this->app->refresh('request', $guard, 'setRequest');
  6. });
  7. });
  8. }
  9. protected function makeGuard(array $config)
  10. {
  11. return new RequestGuard(function ($request) use ($config) {
  12. return (new TokenGuard(
  13. $this->app->make(ResourceServer::class),
  14. Auth::createUserProvider($config['provider']),
  15. $this->app->make(TokenRepository::class),
  16. $this->app->make(ClientRepository::class),
  17. $this->app->make('encrypter')
  18. ))->user($request);
  19. }, $this->app['request']);
  20. }

授权码模式

授权码模式大概分为 5 个步骤:

  • 第三方 向我们的服务器申请创建客户端。
  • 用户打开客户端以后,客户端会跳转到我们的网站授权页面要求用户给予授权。
  • 用户同意给予客户端授权,我们将会返回 授权码
  • 客户端使用上一步获得的授权,向认证服务器申请令牌。
  • 客户端使用令牌,向资源服务器申请获取资源。

为何授权码模式需要如此设置步骤可以查看:Why is there an “Authorization Code” flow in OAuth2 when “Implicit” flow works so well?OAuth2疑问解答

创建客户端

在创建客户端这一步骤,第三方需要提供客户端名称与客户端的 redirect

  1. const data = {
  2. name: 'Client Name',
  3. redirect: 'http://example.com/callback'
  4. };
  5. axios.post('/oauth/clients', data)
  6. .then(response => {
  7. console.log(response.data);
  8. })
  9. .catch (response => {
  10. // List errors on response...
  11. });

我们在创建成功之后,会返回此客户端的 ID 和密钥。这两个东西十分重要,是后面几个步骤必要的参数。

  1. public function forClients()
  2. {
  3. $this->router->group(['middleware' => ['web', 'auth']], function ($router) {
  4. $router->get('/clients', [
  5. 'uses' => 'ClientController@forUser',
  6. ]);
  7. $router->post('/clients', [
  8. 'uses' => 'ClientController@store',
  9. ]);
  10. $router->put('/clients/{client_id}', [
  11. 'uses' => 'ClientController@update',
  12. ]);
  13. $router->delete('/clients/{client_id}', [
  14. 'uses' => 'ClientController@destroy',
  15. ]);
  16. });
  17. }
  18. public function store(Request $request)
  19. {
  20. $this->validation->make($request->all(), [
  21. 'name' => 'required|max:255',
  22. 'redirect' => 'required|url',
  23. ])->validate();
  24. return $this->clients->create(
  25. $request->user()->getKey(), $request->name, $request->redirect
  26. )->makeVisible('secret');
  27. }
  28. public function create($userId, $name, $redirect, $personalAccess = false, $password = false)
  29. {
  30. $client = (new Client)->forceFill([
  31. 'user_id' => $userId,
  32. 'name' => $name,
  33. 'secret' => str_random(40),
  34. 'redirect' => $redirect,
  35. 'personal_access_client' => $personalAccess,
  36. 'password_client' => $password,
  37. 'revoked' => false,
  38. ]);
  39. $client->save();
  40. return $client;
  41. }

跳转授权页面

客户端创建之后,开发者会使用此客户端的 ID 和密钥来请求授权代码,并从应用程序访问令牌。首先,接入应用的用户向你应用程序的 /oauth/authorize 路由发出重定向请求,

  1. Route::get('/redirect', function () {
  2. $query = http_build_query([
  3. 'client_id' => 'client-id',
  4. 'redirect_uri' => 'http://example.com/callback',
  5. 'response_type' => 'code',
  6. 'scope' => '',
  7. ]);
  8. return redirect('http://your-app.com/oauth/authorize?'.$query);
  9. });

这个链接会访问我们的授权路由,我们的服务器会验证上面的四个参数,考察是否存在这个第三方客户端,如果验证通过,将会渲染出我们的授权页面。

  1. public function forAuthorization()
  2. {
  3. $this->router->group(['middleware' => ['web', 'auth']], function ($router) {
  4. $router->get('/authorize', [
  5. 'uses' => 'AuthorizationController@authorize',
  6. ]);
  7. $router->post('/authorize', [
  8. 'uses' => 'ApproveAuthorizationController@approve',
  9. ]);
  10. $router->delete('/authorize', [
  11. 'uses' => 'DenyAuthorizationController@deny',
  12. ]);
  13. });
  14. }
  15. public function authorize(ServerRequestInterface $psrRequest,
  16. Request $request,
  17. ClientRepository $clients,
  18. TokenRepository $tokens)
  19. {
  20. return $this->withErrorHandling(function () use ($psrRequest, $request, $clients, $tokens) {
  21. $authRequest = $this->server->validateAuthorizationRequest($psrRequest);
  22. $scopes = $this->parseScopes($authRequest);
  23. $token = $tokens->findValidToken(
  24. $user = $request->user(),
  25. $client = $clients->find($authRequest->getClient()->getIdentifier())
  26. );
  27. if ($token && $token->scopes === collect($scopes)->pluck('id')->all()) {
  28. return $this->approveRequest($authRequest, $user);
  29. }
  30. $request->session()->put('authRequest', $authRequest);
  31. return $this->response->view('passport::authorize', [
  32. 'client' => $client,
  33. 'user' => $user,
  34. 'scopes' => $scopes,
  35. 'request' => $request,
  36. ]);
  37. });
  38. }

这里最关键的就是 validateAuthorizationRequest 这个函数:

  1. public function validateAuthorizationRequest(ServerRequestInterface $request)
  2. {
  3. foreach ($this->enabledGrantTypes as $grantType) {
  4. if ($grantType->canRespondToAuthorizationRequest($request)) {
  5. return $grantType->validateAuthorizationRequest($request);
  6. }
  7. }
  8. throw OAuthServerException::unsupportedGrantType();
  9. }

canRespondToAuthorizationRequest 用于验证授权模式与参数的 response_type 是否符合。如果确认授权模式正确,那么接下来就会继续验证以下几项:

  • 客户端 id
  • redirect 重定向地址
  • scopes 授权范围
  • state 客户端状态

客户端

  1. public function validateAuthorizationRequest(ServerRequestInterface $request)
  2. {
  3. $clientId = $this->getQueryStringParameter(
  4. 'client_id',
  5. $request,
  6. $this->getServerParameter('PHP_AUTH_USER', $request)
  7. );
  8. if (is_null($clientId)) {
  9. throw OAuthServerException::invalidRequest('client_id');
  10. }
  11. $client = $this->clientRepository->getClientEntity(
  12. $clientId,
  13. $this->getIdentifier(),
  14. null,
  15. false
  16. );
  17. if ($client instanceof ClientEntityInterface === false) {
  18. $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
  19. throw OAuthServerException::invalidClient();
  20. }
  21. ...
  22. }
  23. public function getIdentifier()
  24. {
  25. return 'authorization_code';
  26. }

客户端的验证主要是利用请求中的参数 client_id,我们会从表 oauth_clients 的表中按照 client_id 来取出数据库记录:

  1. public function getClientEntity($clientIdentifier, $grantType,
  2. $clientSecret = null, $mustValidateSecret = true)
  3. {
  4. $record = $this->clients->findActive($clientIdentifier);
  5. if (! $record || ! $this->handlesGrant($record, $grantType)) {
  6. return;
  7. }
  8. $client = new Client(
  9. $clientIdentifier, $record->name, $record->redirect
  10. );
  11. if ($mustValidateSecret &&
  12. ! hash_equals($record->secret, (string) $clientSecret)) {
  13. return;
  14. }
  15. return $client;
  16. }
  17. public function findActive($id)
  18. {
  19. $client = $this->find($id);
  20. return $client && ! $client->revoked ? $client : null;
  21. }
  22. protected function handlesGrant($record, $grantType)
  23. {
  24. switch ($grantType) {
  25. case 'authorization_code':
  26. return ! $record->firstParty();
  27. case 'personal_access':
  28. return $record->personal_access_client;
  29. case 'password':
  30. return $record->password_client;
  31. default:
  32. return true;
  33. }
  34. }

在表 oauth_clients 中还有两个字段 personal_accesspassword,对于授权码模式来说这两个字段都要求为 0。

重定向地址

  1. public function validateAuthorizationRequest(ServerRequestInterface $request)
  2. {
  3. ...
  4. $redirectUri = $this->getQueryStringParameter('redirect_uri', $request);
  5. if ($redirectUri !== null) {
  6. if (
  7. is_string($client->getRedirectUri())
  8. && (strcmp($client->getRedirectUri(), $redirectUri) !== 0)
  9. ) {
  10. $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
  11. throw OAuthServerException::invalidClient();
  12. } elseif (
  13. is_array($client->getRedirectUri())
  14. && in_array($redirectUri, $client->getRedirectUri()) === false
  15. ) {
  16. $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
  17. throw OAuthServerException::invalidClient();
  18. }
  19. } elseif (is_array($client->getRedirectUri()) && count($client->getRedirectUri()) !== 1
  20. || empty($client->getRedirectUri())
  21. ) {
  22. $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
  23. throw OAuthServerException::invalidClient();
  24. }
  25. ...
  26. }

这部分验证参数中的 redirect_uri 是否与数据库中的重定向地址是否一致。

授权作用域

授权作用域可以让 API 客户端在请求账户授权时请求特定的权限。例如,如果你正在构建电子商务应用程序,并不是所有接入的 API 应用都需要下订单的功能。你可以让接入的 API 应用只被允许授权访问订单发货状态。换句话说,作用域允许应用程序的用户限制第三方应用程序执行的操作。

你可以在 AuthServiceProvider 的 boot 方法中使用 Passport::tokensCan 方法来定义 API 的作用域。tokensCan 方法接受一个作用域名称、描述的数组作为参数。作用域描述将会在授权确认页中直接展示给用户,你可以将其定义为任何你需要的内容:

  1. Passport::tokensCan([
  2. 'place-orders' => 'Place orders',
  3. 'check-status' => 'Check order status',
  4. ]);
  5. public static function tokensCan(array $scopes)
  6. {
  7. static::$scopes = $scopes;
  8. }

验证授权作用域的时候,只是在 Passport 中验证是否存在该授权作用域:

  1. public function validateAuthorizationRequest(ServerRequestInterface $request)
  2. {
  3. ...
  4. $scopes = $this->validateScopes(
  5. $this->getQueryStringParameter('scope', $request, $this->defaultScope),
  6. is_array($client->getRedirectUri())
  7. ? $client->getRedirectUri()[0]
  8. : $client->getRedirectUri()
  9. );
  10. ...
  11. }
  12. public function validateScopes($scopes, $redirectUri = null)
  13. {
  14. $scopesList = array_filter(explode(self::SCOPE_DELIMITER_STRING, trim($scopes)), function ($scope) {
  15. return !empty($scope);
  16. });
  17. $validScopes = [];
  18. foreach ($scopesList as $scopeItem) {
  19. $scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeItem);
  20. if ($scope instanceof ScopeEntityInterface === false) {
  21. throw OAuthServerException::invalidScope($scopeItem, $redirectUri);
  22. }
  23. $validScopes[] = $scope;
  24. }
  25. return $validScopes;
  26. }
  27. public function getScopeEntityByIdentifier($identifier)
  28. {
  29. if (Passport::hasScope($identifier)) {
  30. return new Scope($identifier);
  31. }
  32. }

state

这个字段用于防止 csrf 攻击的,具体可以查看 :移花接木:针对OAuth2的CSRF攻击

  1. public function validateAuthorizationRequest(ServerRequestInterface $request)
  2. {
  3. $stateParameter = $this->getQueryStringParameter('state', $request);
  4. $authorizationRequest = new AuthorizationRequest();
  5. $authorizationRequest->setGrantTypeId($this->getIdentifier());
  6. $authorizationRequest->setClient($client);
  7. $authorizationRequest->setRedirectUri($redirectUri);
  8. $authorizationRequest->setState($stateParameter);
  9. $authorizationRequest->setScopes($scopes);
  10. }

验证结束后,接下来就会验证当前用户是否已经授权过,如果已经授权过,那么就会直接返回授权码,否则就会渲染授权页面:

  1. public function authorize(ServerRequestInterface $psrRequest,
  2. Request $request,
  3. ClientRepository $clients,
  4. TokenRepository $tokens)
  5. {
  6. return $this->withErrorHandling(function () use ($psrRequest, $request, $clients, $tokens) {
  7. $authRequest = $this->server->validateAuthorizationRequest($psrRequest);
  8. $scopes = $this->parseScopes($authRequest);
  9. $token = $tokens->findValidToken(
  10. $user = $request->user(),
  11. $client = $clients->find($authRequest->getClient()->getIdentifier())
  12. );
  13. if ($token && $token->scopes === collect($scopes)->pluck('id')->all()) {
  14. return $this->approveRequest($authRequest, $user);
  15. }
  16. $request->session()->put('authRequest', $authRequest);
  17. return $this->response->view('passport::authorize', [
  18. 'client' => $client,
  19. 'user' => $user,
  20. 'scopes' => $scopes,
  21. 'request' => $request,
  22. ]);
  23. });
  24. }

验证用户的是否授权首先是查看授权作用域是否与数据库保持一致。由于授权作用域与 token 相互关联,并非与客户端相互关联,所以 scopes 没有在 oauth_clients 表中,而是在 oauth_access_tokens 这个表中。

  1. protected function parseScopes($authRequest)
  2. {
  3. return Passport::scopesFor(
  4. collect($authRequest->getScopes())->map(function ($scope) {
  5. return $scope->getIdentifier();
  6. })->all()
  7. );
  8. }
  9. public static function scopesFor(array $ids)
  10. {
  11. return collect($ids)->map(function ($id) {
  12. if (isset(static::$scopes[$id])) {
  13. return new Scope($id, static::$scopes[$id]);
  14. }
  15. return;
  16. })->filter()->values()->all();
  17. }

可以看到,作用域的 identifier 就是 Scopeid

获取已授权 token

token 的获取主要是利用 client_iduser_id 在表 oauth_access_tokens 中查询符合条件的 token

  1. public function findValidToken($user, $client)
  2. {
  3. return $client->tokens()
  4. ->whereUserId($user->getKey())
  5. ->whereRevoked(0)
  6. ->where('expires_at', '>', Carbon::now())
  7. ->latest('expires_at')
  8. ->first();
  9. }
  10. public function tokens()
  11. {
  12. return $this->hasMany(Token::class, 'client_id');
  13. }

在获取到有效的 token 之后,并且 token 的作用域符合请求参数,就会立即返回,不需要用户的重复授权:

  1. protected function approveRequest($authRequest, $user)
  2. {
  3. $authRequest->setUser(new User($user->getKey()));
  4. $authRequest->setAuthorizationApproved(true);
  5. return $this->convertResponse(
  6. $this->server->completeAuthorizationRequest($authRequest, new Psr7Response)
  7. );
  8. }

授权成功

用户点击确认按钮,授权成功之后,服务器就会跳转到客户端预设的 redirecturi,并且携带授权码等一系列参数

  1. $router->post('/authorize', [
  2. 'uses' => 'ApproveAuthorizationController@approve',
  3. ]);
  4. public function approve(Request $request)
  5. {
  6. return $this->withErrorHandling(function () use ($request) {
  7. $authRequest = $this->getAuthRequestFromSession($request);
  8. return $this->convertResponse(
  9. $this->server->completeAuthorizationRequest($authRequest, new Psr7Response)
  10. );
  11. });
  12. }

completeAuthorizationRequest 是授权服务器的重要步骤:

  1. public function completeAuthorizationRequest(AuthorizationRequest $authRequest, ResponseInterface $response)
  2. {
  3. return $this->enabledGrantTypes[$authRequest->getGrantTypeId()]
  4. ->completeAuthorizationRequest($authRequest)
  5. ->generateHttpResponse($response);
  6. }
  7. public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
  8. {
  9. if ($authorizationRequest->getUser() instanceof UserEntityInterface === false) {
  10. throw new \LogicException('An instance of UserEntityInterface should be set on the AuthorizationRequest');
  11. }
  12. $finalRedirectUri = ($authorizationRequest->getRedirectUri() === null)
  13. ? is_array($authorizationRequest->getClient()->getRedirectUri())
  14. ? $authorizationRequest->getClient()->getRedirectUri()[0]
  15. : $authorizationRequest->getClient()->getRedirectUri()
  16. : $authorizationRequest->getRedirectUri();
  17. // The user approved the client, redirect them back with an auth code
  18. if ($authorizationRequest->isAuthorizationApproved() === true) {
  19. $authCode = $this->issueAuthCode(
  20. $this->authCodeTTL,
  21. $authorizationRequest->getClient(),
  22. $authorizationRequest->getUser()->getIdentifier(),
  23. $authorizationRequest->getRedirectUri(),
  24. $authorizationRequest->getScopes()
  25. );
  26. $payload = [
  27. 'client_id' => $authCode->getClient()->getIdentifier(),
  28. 'redirect_uri' => $authCode->getRedirectUri(),
  29. 'auth_code_id' => $authCode->getIdentifier(),
  30. 'scopes' => $authCode->getScopes(),
  31. 'user_id' => $authCode->getUserIdentifier(),
  32. 'expire_time' => (new \DateTime())->add($this->authCodeTTL)->format('U'),
  33. 'code_challenge' => $authorizationRequest->getCodeChallenge(),
  34. 'code_challenge_method' => $authorizationRequest->getCodeChallengeMethod(),
  35. ];
  36. $response = new RedirectResponse();
  37. $response->setRedirectUri(
  38. $this->makeRedirectUri(
  39. $finalRedirectUri,
  40. [
  41. 'code' => $this->encrypt(
  42. json_encode(
  43. $payload
  44. )
  45. ),
  46. 'state' => $authorizationRequest->getState(),
  47. ]
  48. )
  49. );
  50. return $response;
  51. }
  52. // The user denied the client, redirect them back with an error
  53. throw OAuthServerException::accessDenied(
  54. 'The user denied the request',
  55. $this->makeRedirectUri(
  56. $finalRedirectUri,
  57. [
  58. 'state' => $authorizationRequest->getState(),
  59. ]
  60. )
  61. );
  62. }

这里最重要的就是 issueAuthCode 生成授权码:

  1. protected function issueAuthCode(
  2. \DateInterval $authCodeTTL,
  3. ClientEntityInterface $client,
  4. $userIdentifier,
  5. $redirectUri,
  6. array $scopes = []
  7. ) {
  8. $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
  9. $authCode = $this->authCodeRepository->getNewAuthCode();
  10. $authCode->setExpiryDateTime((new \DateTime())->add($authCodeTTL));
  11. $authCode->setClient($client);
  12. $authCode->setUserIdentifier($userIdentifier);
  13. $authCode->setRedirectUri($redirectUri);
  14. foreach ($scopes as $scope) {
  15. $authCode->addScope($scope);
  16. }
  17. while ($maxGenerationAttempts-- > 0) {
  18. $authCode->setIdentifier($this->generateUniqueIdentifier());
  19. try {
  20. $this->authCodeRepository->persistNewAuthCode($authCode);
  21. return $authCode;
  22. } catch (UniqueTokenIdentifierConstraintViolationException $e) {
  23. if ($maxGenerationAttempts === 0) {
  24. throw $e;
  25. }
  26. }
  27. }
  28. }

其中 generateUniqueIdentifier 就是生成授权码的步骤,这个授权码也是表 oauth_auth_codesid

  1. protected function generateUniqueIdentifier($length = 40)
  2. {
  3. try {
  4. return bin2hex(random_bytes($length));
  5. // @codeCoverageIgnoreStart
  6. } catch (\TypeError $e) {
  7. throw OAuthServerException::serverError('An unexpected error has occurred');
  8. } catch (\Error $e) {
  9. throw OAuthServerException::serverError('An unexpected error has occurred');
  10. } catch (\Exception $e) {
  11. // If you get this message, the CSPRNG failed hard.
  12. throw OAuthServerException::serverError('Could not generate a random string');
  13. }
  14. // @codeCoverageIgnoreEnd
  15. }
  16. public function persistNewAuthCode(AuthCodeEntityInterface $authCodeEntity)
  17. {
  18. $this->database->table('oauth_auth_codes')->insert([
  19. 'id' => $authCodeEntity->getIdentifier(),
  20. 'user_id' => $authCodeEntity->getUserIdentifier(),
  21. 'client_id' => $authCodeEntity->getClient()->getIdentifier(),
  22. 'scopes' => $this->formatScopesForStorage($authCodeEntity->getScopes()),
  23. 'revoked' => false,
  24. 'expires_at' => $authCodeEntity->getExpiryDateTime(),
  25. ]);
  26. }

授权码转为令牌

由于 client_id 是公开的,因此上一步授权码的获取理论上很容易,真正重要的是授权码转为令牌:

  1. Route::get('/callback', function (Request $request) {
  2. $http = new GuzzleHttp\Client;
  3. $response = $http->post('http://your-app.com/oauth/token', [
  4. 'form_params' => [
  5. 'grant_type' => 'authorization_code',
  6. 'client_id' => 'client-id',
  7. 'client_secret' => 'client-secret',
  8. 'redirect_uri' => 'http://example.com/callback',
  9. 'code' => $request->code,
  10. ],
  11. ]);
  12. return json_decode((string) $response->getBody(), true);
  13. });

这一步需要客户端提供注册时返回的密码,

  1. public function forAccessTokens()
  2. {
  3. $this->router->post('/token', [
  4. 'uses' => 'AccessTokenController@issueToken',
  5. 'middleware' => 'throttle',
  6. ]);
  7. }
  8. public function issueToken(ServerRequestInterface $request)
  9. {
  10. return $this->withErrorHandling(function () use ($request) {
  11. return $this->convertResponse(
  12. $this->server->respondToAccessTokenRequest($request, new Psr7Response)
  13. );
  14. });
  15. }

这一步需要验证的东西非常繁多,我们分部分来看:

客户端验证

客户端验证主要校验 client_idclient_secretredirect_uri :

  1. public function respondToAccessTokenRequest(
  2. ServerRequestInterface $request,
  3. ResponseTypeInterface $responseType,
  4. \DateInterval $accessTokenTTL
  5. ) {
  6. $client = $this->validateClient($request);
  7. ...
  8. }
  9. protected function validateClient(ServerRequestInterface $request)
  10. {
  11. list($basicAuthUser, $basicAuthPassword) = $this->getBasicAuthCredentials($request);
  12. $clientId = $this->getRequestParameter('client_id', $request, $basicAuthUser);
  13. // If the client is confidential require the client secret
  14. $clientSecret = $this->getRequestParameter('client_secret', $request, $basicAuthPassword);
  15. $client = $this->clientRepository->getClientEntity(
  16. $clientId,
  17. $this->getIdentifier(),
  18. $clientSecret,
  19. true
  20. );
  21. $redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
  22. return $client;
  23. }
  24. protected function getBasicAuthCredentials(ServerRequestInterface $request)
  25. {
  26. if (!$request->hasHeader('Authorization')) {
  27. return [null, null];
  28. }
  29. $header = $request->getHeader('Authorization')[0];
  30. if (strpos($header, 'Basic ') !== 0) {
  31. return [null, null];
  32. }
  33. if (!($decoded = base64_decode(substr($header, 6)))) {
  34. return [null, null];
  35. }
  36. if (strpos($decoded, ':') === false) {
  37. return [null, null]; // HTTP Basic header without colon isn't valid
  38. }
  39. return explode(':', $decoded, 2);
  40. }

验证授权码

客户端的密码验证通过后,就会开始验证授权码,授权码的验证主要涉及 expire_timeclient_idauth_code_id:

  1. public function respondToAccessTokenRequest(
  2. ServerRequestInterface $request,
  3. ResponseTypeInterface $responseType,
  4. \DateInterval $accessTokenTTL
  5. ) {
  6. ...
  7. $encryptedAuthCode = $this->getRequestParameter('code', $request, null);
  8. if ($encryptedAuthCode === null) {
  9. throw OAuthServerException::invalidRequest('code');
  10. }
  11. try {
  12. $authCodePayload = json_decode($this->decrypt($encryptedAuthCode));
  13. if (time() > $authCodePayload->expire_time) {
  14. throw OAuthServerException::invalidRequest('code', 'Authorization code has expired');
  15. }
  16. if ($this->authCodeRepository->isAuthCodeRevoked($authCodePayload->auth_code_id) === true) {
  17. throw OAuthServerException::invalidRequest('code', 'Authorization code has been revoked');
  18. }
  19. if ($authCodePayload->client_id !== $client->getIdentifier()) {
  20. throw OAuthServerException::invalidRequest('code', 'Authorization code was not issued to this client');
  21. }
  22. // The redirect URI is required in this request
  23. $redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
  24. if (empty($authCodePayload->redirect_uri) === false && $redirectUri === null) {
  25. throw OAuthServerException::invalidRequest('redirect_uri');
  26. }
  27. if ($authCodePayload->redirect_uri !== $redirectUri) {
  28. throw OAuthServerException::invalidRequest('redirect_uri', 'Invalid redirect URI');
  29. }
  30. } catch (\LogicException $e) {
  31. throw OAuthServerException::invalidRequest('code', 'Cannot decrypt the authorization code');
  32. }
  33. }
  34. public function isAuthCodeRevoked($codeId)
  35. {
  36. return $this->database->table('oauth_auth_codes')
  37. ->where('id', $codeId)->where('revoked', 1)->exists();
  38. }

发放令牌

令牌的发放主要是 access_tokenrefresh_token,并且取消相关的授权码:

  1. public function respondToAccessTokenRequest(
  2. ServerRequestInterface $request,
  3. ResponseTypeInterface $responseType,
  4. \DateInterval $accessTokenTTL
  5. ) {
  6. // Issue and persist access + refresh tokens
  7. $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $authCodePayload->user_id, $scopes);
  8. $refreshToken = $this->issueRefreshToken($accessToken);
  9. // Inject tokens into response type
  10. $responseType->setAccessToken($accessToken);
  11. $responseType->setRefreshToken($refreshToken);
  12. // Revoke used auth code
  13. $this->authCodeRepository->revokeAuthCode($authCodePayload->auth_code_id);
  14. return $responseType;
  15. }

首先需要生成 access_token,之后再对表 oauth_access_tokens 持久化 access_token

  1. protected function issueAccessToken(
  2. \DateInterval $accessTokenTTL,
  3. ClientEntityInterface $client,
  4. $userIdentifier,
  5. array $scopes = []
  6. ) {
  7. $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
  8. $accessToken = $this->accessTokenRepository->getNewToken($client, $scopes, $userIdentifier);
  9. $accessToken->setClient($client);
  10. $accessToken->setUserIdentifier($userIdentifier);
  11. $accessToken->setExpiryDateTime((new \DateTime())->add($accessTokenTTL));
  12. foreach ($scopes as $scope) {
  13. $accessToken->addScope($scope);
  14. }
  15. while ($maxGenerationAttempts-- > 0) {
  16. $accessToken->setIdentifier($this->generateUniqueIdentifier());
  17. try {
  18. $this->accessTokenRepository->persistNewAccessToken($accessToken);
  19. return $accessToken;
  20. } catch (UniqueTokenIdentifierConstraintViolationException $e) {
  21. if ($maxGenerationAttempts === 0) {
  22. throw $e;
  23. }
  24. }
  25. }
  26. }
  27. public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null)
  28. {
  29. return new AccessToken($userIdentifier, $scopes);
  30. }
  31. protected function generateUniqueIdentifier($length = 40)
  32. {
  33. try {
  34. return bin2hex(random_bytes($length));
  35. // @codeCoverageIgnoreStart
  36. } catch (\TypeError $e) {
  37. throw OAuthServerException::serverError('An unexpected error has occurred');
  38. } catch (\Error $e) {
  39. throw OAuthServerException::serverError('An unexpected error has occurred');
  40. } catch (\Exception $e) {
  41. // If you get this message, the CSPRNG failed hard.
  42. throw OAuthServerException::serverError('Could not generate a random string');
  43. }
  44. // @codeCoverageIgnoreEnd
  45. }
  46. public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEntity)
  47. {
  48. $this->tokenRepository->create([
  49. 'id' => $accessTokenEntity->getIdentifier(),
  50. 'user_id' => $accessTokenEntity->getUserIdentifier(),
  51. 'client_id' => $accessTokenEntity->getClient()->getIdentifier(),
  52. 'scopes' => $this->scopesToArray($accessTokenEntity->getScopes()),
  53. 'revoked' => false,
  54. 'created_at' => new DateTime,
  55. 'updated_at' => new DateTime,
  56. 'expires_at' => $accessTokenEntity->getExpiryDateTime(),
  57. ]);
  58. $this->events->dispatch(new AccessTokenCreated(
  59. $accessTokenEntity->getIdentifier(),
  60. $accessTokenEntity->getUserIdentifier(),
  61. $accessTokenEntity->getClient()->getIdentifier()
  62. ));
  63. }

类似地,还有生成 refresh_token

  1. protected function issueRefreshToken(AccessTokenEntityInterface $accessToken)
  2. {
  3. $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
  4. $refreshToken = $this->refreshTokenRepository->getNewRefreshToken();
  5. $refreshToken->setExpiryDateTime((new \DateTime())->add($this->refreshTokenTTL));
  6. $refreshToken->setAccessToken($accessToken);
  7. while ($maxGenerationAttempts-- > 0) {
  8. $refreshToken->setIdentifier($this->generateUniqueIdentifier());
  9. try {
  10. $this->refreshTokenRepository->persistNewRefreshToken($refreshToken);
  11. return $refreshToken;
  12. } catch (UniqueTokenIdentifierConstraintViolationException $e) {
  13. if ($maxGenerationAttempts === 0) {
  14. throw $e;
  15. }
  16. }
  17. }
  18. }

BearerToken

为了加强安全性,根据 OAuth2 规范,access_tokenrefresh_token 需要利用 Bearer Token 的方式给出,access token 会被转化为 JWTrefresh token 会被加密:

  1. public function generateHttpResponse(ResponseInterface $response)
  2. {
  3. $expireDateTime = $this->accessToken->getExpiryDateTime()->getTimestamp();
  4. $jwtAccessToken = $this->accessToken->convertToJWT($this->privateKey);
  5. $responseParams = [
  6. 'token_type' => 'Bearer',
  7. 'expires_in' => $expireDateTime - (new \DateTime())->getTimestamp(),
  8. 'access_token' => (string) $jwtAccessToken,
  9. ];
  10. I
  11. if ($this->refreshToken instanceof RefreshTokenEntityInterface) {
  12. $refreshToken = $this->encrypt(
  13. json_encode(
  14. [
  15. 'client_id' => $this->accessToken->getClient()->getIdentifier(),
  16. 'refresh_token_id' => $this->refreshToken->getIdentifier(),
  17. 'access_token_id' => $this->accessToken->getIdentifier(),
  18. 'scopes' => $this->accessToken->getScopes(),
  19. 'user_id' => $this->accessToken->getUserIdentifier(),
  20. 'expire_time' => $this->refreshToken->getExpiryDateTime()->getTimestamp(),
  21. ]
  22. )
  23. );
  24. $responseParams['refresh_token'] = $refreshToken;
  25. }
  26. $responseParams = array_merge($this->getExtraParams($this->accessToken), $responseParams);
  27. $response = $response
  28. ->withStatus(200)
  29. ->withHeader('pragma', 'no-cache')
  30. ->withHeader('cache-control', 'no-store')
  31. ->withHeader('content-type', 'application/json; charset=UTF-8');
  32. $response->getBody()->write(json_encode($responseParams));
  33. return $response;
  34. }

刷新令牌

如果你的应用程序发放了短期的访问令牌,用户将需要通过在发出访问令牌时提供给他们的刷新令牌来刷新其访问令牌。该申请的 url 与申请令牌的链接相同,仅仅 grant_type 不同:

  1. $response = $http->post('http://your-app.com/oauth/token', [
  2. 'form_params' => [
  3. 'grant_type' => 'refresh_token',
  4. 'refresh_token' => 'the-refresh-token',
  5. 'client_id' => 'client-id',
  6. 'client_secret' => 'client-secret',
  7. 'scope' => '',
  8. ],
  9. ]);
  10. return json_decode((string) $response->getBody(), true);
  1. public function respondToAccessTokenRequest(
  2. ServerRequestInterface $request,
  3. ResponseTypeInterface $responseType,
  4. \DateInterval $accessTokenTTL
  5. ) {
  6. // Validate request
  7. $client = $this->validateClient($request);
  8. $oldRefreshToken = $this->validateOldRefreshToken($request, $client->getIdentifier());
  9. $scopes = $this->validateScopes($this->getRequestParameter(
  10. 'scope',
  11. $request,
  12. implode(self::SCOPE_DELIMITER_STRING, $oldRefreshToken['scopes']))
  13. );
  14. // The OAuth spec says that a refreshed access token can have the original scopes or fewer so ensure
  15. // the request doesn't include any new scopes
  16. foreach ($scopes as $scope) {
  17. if (in_array($scope->getIdentifier(), $oldRefreshToken['scopes']) === false) {
  18. throw OAuthServerException::invalidScope($scope->getIdentifier());
  19. }
  20. }
  21. // Expire old tokens
  22. $this->accessTokenRepository->revokeAccessToken($oldRefreshToken['access_token_id']);
  23. $this->refreshTokenRepository->revokeRefreshToken($oldRefreshToken['refresh_token_id']);
  24. // Issue and persist new tokens
  25. $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $oldRefreshToken['user_id'], $scopes);
  26. $refreshToken = $this->issueRefreshToken($accessToken);
  27. // Inject tokens into response
  28. $responseType->setAccessToken($accessToken);
  29. $responseType->setRefreshToken($refreshToken);
  30. return $responseType;
  31. }